package com.test.ad.demo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.test.ad.demo.R;
import com.test.ad.demo.model.AdModel;

import java.text.DecimalFormat;
import java.util.List;

/**
 * 广告记录列表适配器
 */
public class AdRecordAdapter extends BaseAdapter {
    
    private Context context;
    private List<AdModel> adList;
    private LayoutInflater inflater;
    private DecimalFormat decimalFormat;
    
    public AdRecordAdapter(Context context, List<AdModel> adList) {
        this.context = context;
        this.adList = adList;
        this.inflater = LayoutInflater.from(context);
        this.decimalFormat = new DecimalFormat("#.##");
    }
    
    @Override
    public int getCount() {
        return adList != null ? adList.size() : 0;
    }
    
    @Override
    public Object getItem(int position) {
        return adList != null ? adList.get(position) : null;
    }
    
    @Override
    public long getItemId(int position) {
        return position;
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_ad_record, parent, false);
            holder = new ViewHolder();
            holder.tvSerialNumber = convertView.findViewById(R.id.tv_serial_number);
            holder.tvType = convertView.findViewById(R.id.tv_type);
            holder.tvCoins = convertView.findViewById(R.id.tv_coins);
            holder.tvTime = convertView.findViewById(R.id.tv_time);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        
        AdModel ad = adList.get(position);
        
        // 设置序号
        holder.tvSerialNumber.setText(String.valueOf(ad.getId()));
        
        // 设置类型
        holder.tvType.setText(ad.getType().getDisplayName());
        
        // 设置收益（保留两位小数）
        holder.tvCoins.setText(decimalFormat.format(ad.getCoins()));
        
        // 设置时间
        holder.tvTime.setText(ad.getDate());
        
        return convertView;
    }
    
    static class ViewHolder {
        TextView tvSerialNumber;
        TextView tvType;
        TextView tvCoins;
        TextView tvTime;
    }
    
    // 更新数据
    public void updateData(List<AdModel> newAdList) {
        this.adList = newAdList;
        notifyDataSetChanged();
    }
}
